<template>

  <!--  试图-->
  <div>



    <el-dialog title="角色报表" :visible.sync="dialogShowFormVisible">
      <div id="main" style="width: 500px;height: 500px">

      </div>
    </el-dialog>

    <el-dialog title="添加角色" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="roleName" :label-width="formLabelWidth">
          <el-input v-model="form.roleName" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="角色头像" :label-width="formLabelWidth">
          <el-upload
              class="avatar-uploader"
              action="http://192.168.137.44:8888/system/sysrole/uploadRoleHeader/"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>

        </el-form-item>
        <el-form-item label="角色权限字符串" prop="roleKey" :label-width="formLabelWidth">
          <el-input v-model="form.roleKey" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="显示顺序" :label-width="formLabelWidth">
          <el-input-number v-model="form.roleSort" controls-position="right" @change="handleChange" :min="1" :max="10"></el-input-number>
        </el-form-item>

        <el-form-item label="数据范围" :label-width="formLabelWidth">
          <el-select v-model="form.dataScope" placeholder="请选择数据范围">
            <el-option label="全部数据权限" value="1"></el-option>
            <el-option label="自定数据权限" value="2"></el-option>
            <el-option label="本部门数据权限" value="3"></el-option>
            <el-option label="本部门及以下数据权限" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色状态" :label-width="formLabelWidth">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="创建者" :label-width="formLabelWidth">
          <el-input v-model="form.createBy" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="创建时间" :label-width="formLabelWidth">
          <el-date-picker disabled v-model="form.createTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="form.remark" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="菜单权限" :label-width="formLabelWidth">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.deptCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree
              :data="TreeData"
              show-checkbox
              default-expand-all
              node-key="id"
              ref="menu"
              highlight-current
              :props="defaultProps">
          </el-tree>

        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="AddRole('ruleForm')">确 定</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </div>
    </el-dialog>

    <el-form :inline="true" :model="formInline" class="demo-form-inline">


      <el-collapse v-model="activeNames" @change="roleSerchZheChange">
        <el-collapse-item  name="1" style="color: #999;">
          <el-form-item label="角色名称">
            <el-input v-model="formInline.roleName" placeholder="角色名称"></el-input>
          </el-form-item>

          <el-form-item label="角色权限">
            <el-input v-model="formInline.roleKey" placeholder="角色权限"></el-input>
          </el-form-item>

          <el-form-item label="角色状态" :label-width="formLabelWidth">
            <el-select clearable v-model="formInline.status" placeholder="请选择角色状态">
              <el-option label="正常" value="1"></el-option>
              <el-option label="异常" value="0"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="创建时间">
            <el-date-picker
                v-model="value"
                type="daterange"
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="changeDate"
            >
            </el-date-picker>
          </el-form-item>
        </el-collapse-item>
      </el-collapse>



      <div style="width: 1000px;height: 100px">
        <el-form-item>
          <el-button type="primary" plain icon="el-icon-search" @click="getRoleList">查询</el-button>
          <el-button type="success" icon="el-icon-plus" plain @click="OpenAddRole">添加</el-button>
          <el-button type="warning" icon="el-icon-edit-outline" plain @click="OpenUpdateRole">修改</el-button>
          <el-button type="danger" icon="el-icon-download" plain @click="excelPort">导出Excel</el-button>
          <el-button type="success" icon="el-icon-search" plain @click="showRoleForm">展开角色报表</el-button>
          <el-button type="success" icon="el-icon-search" plain @click="loadTemplate">下载模板</el-button>
          <el-upload
              action="http://192.168.137.44:8888/system/sysrole/loadinExcel/"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
              :show-file-list="false">
            <el-button type="primary" icon="el-icon-upload">上传 Excel</el-button>
          </el-upload>

        </el-form-item>
      </div>
    </el-form>

    <el-dialog title="修改角色" :visible.sync="dialogFormVisibleUpdata">
      <el-form :model="formUpdata">
        <el-form-item label="角色名称" :label-width="formLabelWidth">
          <el-input v-model="formUpdata.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色权限字符串" :label-width="formLabelWidth">
          <el-input v-model="formUpdata.roleKey" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="显示顺序" :label-width="formLabelWidth">
          <el-input v-model="formUpdata.roleSort" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="数据范围" :label-width="formLabelWidth">
          <el-select v-model="formUpdata.dataScope" placeholder="请选择数据范围">
            <el-option label="全部数据权限" value="1"></el-option>
            <el-option label="自定数据权限" value="2"></el-option>
            <el-option label="本部门数据权限" value="3"></el-option>
            <el-option label="本部门及以下数据权限" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜单树选择项是否关联显示" :label-width="formLabelWidth">
          <el-radio-group v-model="formUpdata.menuCheckStrictly">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门树选择项是否关联显示" :label-width="formLabelWidth">
          <el-radio-group v-model="formUpdata.deptCheckStrictly">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色状态" :label-width="formLabelWidth">
          <el-radio-group v-model="formUpdata.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="删除标志" :label-width="formLabelWidth">
          <el-radio-group v-model="formUpdata.delFlag">
            <el-radio label="0">存在</el-radio>
            <el-radio label="2">删除</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="创建者" :label-width="formLabelWidth">
          <el-input v-model="formUpdata.createBy" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="创建时间" :label-width="formLabelWidth">
          <el-date-picker v-model="formUpdata.createTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
        </el-form-item>
        <el-form-item label="更新者" :label-width="formLabelWidth">
          <el-input v-model="formUpdata.updateBy" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="更新时间" :label-width="formLabelWidth">
          <el-date-picker disabled v-model="formUpdata.updateTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="formUpdata.remark" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleUpdata = false">取 消</el-button>
        <el-button type="primary" @click="roleUpdate">确 定</el-button>
      </div>
    </el-dialog>

    <el-table
        ref="singleTable"
        :data="tableData"
        highlight-current-row
        @current-change="handleUpdataChange"
        style="width: 100%">
      <el-table-column
          fixed
          prop="headerImage"
          label="角色头像"
          width="150">
        <template v-slot="scope">
          <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.headerImage"
              ></el-image>
        </template>
      </el-table-column>
      <el-table-column
          fixed
          prop="roleId"
          label="角色序号"
          width="150">
      </el-table-column>
      <el-table-column
          prop="roleName"
          label="角色名称"
          width="120">
      </el-table-column>
      <el-table-column
          prop="roleKey"
          label="角色权限"
          width="120">
      </el-table-column>
      <el-table-column
          prop="roleSort"
          label="角色排序"
          width="120">
      </el-table-column>
      <el-table-column
          prop="status"
          label="角色状态"
          width="120">
        <template v-slot="a">
          <el-switch
              v-model="a.row.status"
              active-value="0"
              inactive-value="1"
              active-color="#13ce66"
              inactive-color="#ff4949">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
          prop="createTime"
          label="创建时间"
          width="120">
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          width="100">
        <template slot-scope="scope">
          <el-button @click="delRole(scope.row.roleId)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @current-change="handleCurrentChange"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="total">
    </el-pagination>
  </div>

</template>

<script>
import * as echarts from "echarts";



export default {
  name: "RoleView",
  data() {
    return {
      //默认属性
      imageUrl:'',
      value:'',
      activeNames: ['1'],
      form:{
        headerImage:'',
        menuIds:[],
        menuCheckStrictly: '0',
        deptCheckStrictly: '1',
        createTime: this.formatDate(new Date()),
        delFlag: '0',
        status: '0',
        roleSort: 1,
      },
      formLabelWidth:'120px',
      dialogFormVisible:false,
      tableData:[],
      pageNum:1,
      total:0,
      pageSize:3,
      formInline:{},
      dialogFormVisibleUpdata:false,
      formUpdata:{
        updateTime: this.formatDate(new Date()),
      },
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],roleKey: [
          { required: true, message: '请输入权限字符', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],},
      TreeData:[],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      menuExpand:false,
      menuNodeAll:false,
      dialogShowFormVisible:false,




    }
  }, methods: {
    //自定义方法
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel';
      if (!isExcel) {
        this.$message.error('请上传 Excel 文件！');
        return false;
      }
      return true;
    },
    handleUploadSuccess(response, file, fileList) {
      console.log(response+file+fileList)
      this.$message.success('文件上传成功！');
    },
    handleUploadError(error, file, fileList) {
      console.log(error+file+fileList)
      this.$message.error('文件上传失败！');
    },
    loadTemplate() {
      location.href = "http://192.168.137.44:9000/2112a/exceltemplate/%E7%94%A8%E6%88%B7%E4%BF%A1%E6%81%AF.xlsx";
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.headerImage = res.data;
      console.log(this.form.headerImage)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    showRoleForm() {

      this.dialogShowFormVisible = true;
      // this.initEcharts(); // 在显示对话框时初始化 Echarts
      this.$nextTick(() => {
        this.initEcharts();
      });

    },
    initEcharts() {
      let formData = []
      let value1 = []
      let value2 = []

      const chartDom = document.getElementById('main');
      const myChart = echarts.init(chartDom);

      this.axios.get("system/sysrole/showForm").then(res => {
        formData = res.data;

       value1 = formData.data.map(item => item.roleName);
       value2 = formData.data.map(item => item.valueCount);

        const option = {
          xAxis: {
            type: 'category',
            data: value1  // 直接将获取到的角色名称数组赋值给 xAxis 的 data
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              data: value2,  // 将获取到的数量数组赋值给 series 的 data
              type: 'bar'
            }
          ]
        };
        option && myChart.setOption(option);
      });
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.menuCheckStrictly = value ? '1': '0';
      } else if (type == 'dept') {
        this.form.deptCheckStrictly = value ? '1': '0';
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.TreeData: []);
        console.log(this.TreeData.id)
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.TreeData: []);
      }
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.TreeData;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    roleSerchZheChange(val) {
      console.log(val);
    },
    roleAddGetThreeData() {
      this.axios.get("system/menu/list2").then(res => {
        this.TreeData = res.data.data
      });
    },
    handleChange(num) {
      console.log(num)
      this.form.roleSort = num
      console.log("计数器发生改变添加对象"+this.form.roleSort)
    },
    delRole(roleId) {
      console.log("删除操作")
      this.axios.get("system/sysrole/delRole", {params: {roleId: roleId}}).then(res => {
        if (res.data.code == 200) {
          this.$message.success(res.data.msg);
          this.getRoleList();
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    excelPort() {
      location.href = "http://192.168.137.44:9017/sysrole/excelPort";
    },
    roleUpdate() {
      this.axios.post("system/sysrole/updataRole", this.formUpdata).then(res => {
        if (res.data.code == 200) {
          this.$message.success(res.data.msg);
          this.dialogFormVisibleUpdata = false;
        } else {
          this.$message.error(res.data.msg)
        }
      });
    },
    OpenUpdateRole() {
      console.log(this.formUpdata)
      if (Object.keys(this.formUpdata).length===1) {
        console.log("已执行判断修改对象非空")
          this.$message.error("请选择角色数据")
          return;
      }
      this.dialogFormVisibleUpdata = true;
    },
    handleUpdataChange(currentRow) {
      console.log(currentRow)
      this.formUpdata = currentRow
      this.formUpdata.updateTime = this.formatDate(new Date());
    },
    changeDate(value){
      this.value=value;

      if(this.value!=null){
        this.formInline.startTime=this.value[0];
        this.formInline.endTime=this.value[1]
      }else{
        this.formInline.startTime=""
        this.formInline.endTime="";
      }

    },
    AddRole(formName) {
      console.log("添加对象="+this.form.headerImage)
      this.form.menuIds = this.$refs.menu.getCheckedKeys();
      console.log("菜单选中的值"+this.form.menuIds)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.axios.post("system/sysrole/roleAdd", this.form).then(res => {
            if (res.data.code == 200) {
              this.$message.success(res.data.msg);
              this.dialogFormVisible = false;
              this.$router.push("role")
            } else {
              this.$message.error(res.data.msg);
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    OpenAddRole() {
      console.log(this.form)
      this.form = {
        headerImage:'',
        menuIds:[],
        menuCheckStrictly: '0',
        deptCheckStrictly: '1',
        createTime: this.formatDate(new Date()),
        delFlag: '0',
        status: '0',
        roleSort: 1,
      }
     this.roleAddGetThreeData();
      console.log("树型菜单"+this.TreeData.data)
        this.dialogFormVisible = true
    },
    handleCurrentChange(page) {
      this.pageNum = page;
      this.getRoleList();
    },
    getRoleList() {
      this.axios.get("system/sysrole/roleList",{
        params:{
          startTime:this.formInline.startTime,
          endTime:this.formInline.endTime,
          roleName:this.formInline.roleName,
          roleKey:this.formInline.roleKey,
          status:this.formInline.status,
          pageNum:this.pageNum,
          pageSize:this.pageSize
        }
      }).then(res => {
        this.tableData = res.data.data.list
        this.total = res.data.data.total
      });
    },

  }, created() {//初始化
      this.getRoleList();
  }
}
</script>

<style scoped>

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>